package com.spic.business.alarm.utils;

import com.alibaba.fastjson.JSON;
import com.spic.business.alarm.config.ProjectInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class JsonFileUtils
{
    private static final Logger log = LoggerFactory.getLogger(JsonFileUtils.class);

    public static String readJsonFile(String fileName) throws Exception {
        File jsonFile = new File(fileName);
        return readJsonFile(jsonFile);
    }

    public static String readJsonFile(File jsonFile) throws Exception {
        FileReader fileReader = new FileReader(jsonFile);
        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1)
            sb.append((char)ch);
        fileReader.close();
        reader.close();
        return sb.toString();
    }

    public static boolean writeJsonFile(String filePath, String jsonString) {
        try {
            FileWriter fw = new FileWriter(filePath);
            PrintWriter out = new PrintWriter(fw);
            out.write(jsonString);
            out.println();
            fw.close();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean writeJsonFileWithFormat(String filePath, String jsonString) {
        return writeJsonFile(filePath, formatJson(jsonString));
    }

    public static String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr))
            return "";
        StringBuilder sb = new StringBuilder();
        char last = Character.MIN_VALUE;
        char current = Character.MIN_VALUE;
        int indent = 0;
        boolean isInQuotationMarks = false;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '"':
                    if (last != '\\')
                        isInQuotationMarks = !isInQuotationMarks;
                    sb.append(current);
                    break;
                case '[':
                case '{':
                    sb.append(current);
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent++;
                        addIndentBlank(sb, indent);
                    }
                    break;
                case ']':
                case '}':
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent--;
                        addIndentBlank(sb, indent);
                    }
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\' && !isInQuotationMarks) {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
                    break;
            }
        }
        return sb.toString();
    }

    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++)
            sb.append('\t');
    }

    /**
     * 读取 resources 下的文件
     * @return
     */
    public static ProjectInfo getProjectConfig() {
        ProjectInfo config = null;
        String txt = "";
        try {
            Resource classPathResource = new ClassPathResource("ProjectConfig.json");
            InputStream inputStream = classPathResource.getInputStream();
            boolean exists = classPathResource.exists();
            StringBuilder buffer = new StringBuilder();
            byte[] bytes = new byte[1024];
            try {
                for (int n; (n = inputStream.read(bytes)) != -1; ) {
                    buffer.append(new String(bytes, 0, n,"utf-8")); //设置编码 不然服务器会解析json失败
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            txt = buffer.toString();
            if (exists) {
                config = (ProjectInfo) JSON.parseObject(txt, ProjectInfo.class);
                log.info(config.toString());
            } else {
                log.error("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("{}", e.getMessage());
        }
        return config;
    }

    public static void main(String[] args) {
        ProjectInfo projectInfo = getProjectConfig();
        System.out.println(JSON.toJSONString(projectInfo));
    }
}

